//
//  Table_ViewController.m
//  helloword
//
//  Created by chen on 17/2/27.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "TableViewController.h"
#import "CountryInfo.h"
#import "FxString.h"

#define CellIdentifier @"CellIdentifier"

@interface TableViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating>
@property (strong, nonatomic) IBOutlet UITextField *txtField;

//存放国家信息副本
@property (strong,nonatomic) NSMutableArray<CountryInfo *> *countrys;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)UISearchController *searchController;
//存放过滤后的数据
@property(strong,nonatomic)NSArray *listFilterTeams;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    //设置导航栏
    self.navigationItem.title = @"单元格插入和删除";
//    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //设置单元格文本框
    self.txtField.hidden = TRUE;
    self.txtField.delegate = self;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [self initCountry];
    [self initSearchBar];
    [self test];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [_searchController.searchBar endEditing:YES ];
}
-(void) initCountry{
    NSArray *arrCodes = [NSLocale ISOCountryCodes];
    NSLocale *locale = [NSLocale currentLocale];
    CountryInfo *info;
    _countrys = [[NSMutableArray alloc] init];
    for (NSString *code in arrCodes){
        info = [CountryInfo new];
        info.name = [locale displayNameForKey:NSLocaleCountryCode value:code];
        info.code = code;
        
        [_countrys addObject:info];
    }
    _listFilterTeams = _countrys;
}
-(void) initSearchBar{
    [self filterContentForSearchText:@"" scope:-1];
    //实例化UISearchController
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    //设置self为更新搜索结果对象
    _searchController.searchResultsUpdater = self;
    //在搜索是背景设置为灰色
    _searchController.dimsBackgroundDuringPresentation = FALSE;
    //设置搜索栏放中的按钮
    _searchController.searchBar.scopeButtonTitles = @[@"中文",@"英文"];
    _searchController.searchBar.delegate = self;
    //将搜索栏放到表视图的表头中去
    _tableView.tableHeaderView = _searchController.searchBar;
    [_searchController.searchBar sizeToFit];
    
}
#pragma mark - SearchController方法
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSUInteger)scope{
    if ([searchText length] == 0) {
        _countrys = [NSMutableArray arrayWithArray:_listFilterTeams];
        return;
    }
    NSPredicate *scopePredicate;
    NSArray *tempArray;
    switch (scope) {
        case 0://中文
            scopePredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
            tempArray = [_listFilterTeams filteredArrayUsingPredicate:scopePredicate];
            _countrys = [NSMutableArray arrayWithArray:tempArray];
            break;
        case 1://英文
            scopePredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
            tempArray = [_listFilterTeams filteredArrayUsingPredicate:scopePredicate];
            _countrys = [NSMutableArray arrayWithArray:tempArray];
            break;
            
        default:
            break;
    }
}
-(void) test{
    NSArray *array1 = [NSArray arrayWithObjects:@1,@2,@3,@5,@5,@6,@7, nil];
    NSArray *array2 = [NSArray arrayWithObjects:@4,@5, nil];
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF  in %@",array2];
    
    NSArray *temp1 = [array1 filteredArrayUsingPredicate:predicate1];
    
    [temp1 enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"temp1 = %@",obj);
        
    }];
    NSString *test = @"che~nb--!";
    NSLog(@"-------判断结果%d----",[self checkSpecialCharacter:test]);
}
- (BOOL)checkSpecialCharacter:(NSString *)string
{
    NSString *regex = @"^[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:string];
}
#pragma mark -- 实现UISearchBarDelegate协议方法
//这个方法是在选择“中文”或者“英文”的触发动作
-(void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
    [self updateSearchResultsForSearchController:self.searchController];
}
//这个方法是在SearchBar中的text发生改变是调用它
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self updateSearchResultsForSearchController:self.searchController];
}
#pragma mark -- 实现UISearchResultsUpdating协议方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchController.searchBar.text;
    [self filterContentForSearchText:searchString scope:searchController.searchBar.selectedScopeButtonIndex];
    [self.tableView reloadData];
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return [_countrys count]+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //单元格内添加输入项
    BOOL b_addCell = (indexPath.row == (_countrys.count + 1));
    if (!b_addCell) {
        CountryInfo *info = _countrys[indexPath.row];
        cell.textLabel.text = info.name;
        cell.imageView.image = [UIImage imageNamed:[info.code stringByAppendingString: @".png"]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        _txtField.frame = CGRectMake(40, 0, 300, cell.frame.size.height);
        _txtField.borderStyle = UITextBorderStyleNone;
        _txtField.placeholder = @"Add...";
        _txtField.text = @"";
        [cell addSubview:_txtField];
    }
    
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == ([_countrys count] + 1)) {
        return UITableViewCellEditingStyleInsert;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_countrys removeObjectAtIndex: indexPath.row];
        [_tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }else if (editingStyle == UITableViewCellEditingStyleInsert){
        [_countrys insertObject:_txtField.text atIndex:[_countrys count]];
        [_tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }
    [self.tableView reloadData];
}
#pragma mark -- UIViewController生命周期方法
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:TRUE];
    if (editing) {
        _txtField.hidden = FALSE;
    }else{
        _txtField.hidden = TRUE;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
